package List;

import java.awt.*;

public class MyList implements IList{

    static class Node{
        int val;
        Node next;

        public Node(int val) {
            this.val = val;
        }
    }

    private int size=0;
    private Node head=null;


    @Override
    public void addFirst(int data) {
        Node node=new Node(data);
        if (head==null){
            head=node;
        }else {
            node.next=head;
            head=node;
        }
        size++;
    }

    @Override
    public void addLast(int data) {
Node node=new Node(data);
if (head==null){
    head=node;
}else {
    Node cur=head;
    while (cur.next!=null){
        cur=cur.next;
    }
    cur.next=node;
}
size++;
    }

    @Override
    public void addIndex(int index, int data) {
if (index<0||index>size){
    return;
}
Node node=new Node(data);
if (index==0){
    addFirst(data);
}
else if (index==size){
    addLast(data);
}else {
    Node cur=head;
    while (index>1){
        cur=cur.next;
        index--;
    }
    node.next=cur.next;
    cur.next=node;
    size++;
}



    }

    @Override
    public boolean contains(int key) {
        if (head==null){
            return false;
        }
        Node cur=head;
        while (cur!=null){
            if (cur.val==key){
                return true;
            }
            cur=cur.next;
        }
        return false;
    }

    @Override
    public void remove(int key) {
        if (head == null) {
            return;
        }
        Node cur = head;
        if (head.val == key) {
            head = head.next;
            size--;
            return;
        }
        while (cur.next != null) {
            if (cur.next.val == key) {
                cur.next = cur.next.next;
                size--;
                return;
            }
            cur = cur.next;
        }
        if (cur.val==key){
            cur=null;
            size--;
        }
    }
    @Override
    public void removeAllKey(int key) {
        if (head==null){
            return;
        }
while(head.val==key){
    head=head.next;
    size--;
}
        Node cur=head;
Node next=head.next;
while (next.next!=null){
    if (next.val==key){
        cur.next=next.next;
        next=next.next;
        size--;
    }else {
        next=next.next;
    cur=cur.next;
    }
}
if (next.val==key){
    cur.next=null;
    size--;
}

    }

    @Override
    public int size() {
        return size;
    }

    @Override
    public void display() {
Node cur=head;
while (cur!=null){
    System.out.print(cur.val+" ");
    cur=cur.next;
}
        System.out.println();
    }

    @Override
    public void clear() {
        Node cur=head;
        Node next=cur.next;
        while (next!=null){
            cur=null;
            cur=next;
            next=next.next;
        }
        cur=null;
        head=null;
    }
}
